package org.example.events;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class EventsActivity extends ListActivity {
	private EventsData events;
	public static final String[] FROM = {Constants._ID, Constants.TIME, Constants.TITLE};
	public static final String ORDER_BY = Constants.TIME + " DESC";
	private static int[] TO = { R.id.rowid, R.id.time, R.id.title};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        events = new EventsData(this);
        try {
			addEvent("Hello, Android!");
			Cursor cursor = getEvents();
			showEvents(cursor);
		} finally {
			// TODO: handle exception
			events.close();
		}
    }
	private void showEvents(Cursor cursor) {
		// TODO Auto-generated method stub
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
		
		setListAdapter(adapter);
		
		StringBuilder builder = new StringBuilder();
		builder.append("Saved events: \n");
		
		while(cursor.moveToNext())
		{
			long id = cursor.getLong(0);
			long time = cursor.getLong(1);
			String title = cursor.getString(3);
			
			builder.append("id:" + id);
			builder.append("time:" + time);
			builder.append("title:" + title);
		}
		
		TextView view = (TextView)findViewById(R.id.text);
		view.setText(builder);
	}
	private Cursor getEvents() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = events.getReadableDatabase();
		
		Cursor cursor = db.query(Constants.TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
		startManagingCursor(cursor);
		return cursor;
	}
	
	/**
	 * Insert the new record into Events data source
	 * @param string
	 */
	private void addEvent(String string) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = events.getWritableDatabase();
		ContentValues values = new ContentValues();
		
		values.put(Constants.TIME, System.currentTimeMillis());
		values.put(Constants.TITLE, string);
		
		db.insertOrThrow(Constants.TABLE_NAME, null, values);
	}
}